<template>
  <div class="form-container">
    <!-- 添加标题 -->
    <div class="header">编辑运动场信息</div>
    <!-- 添加带下划线的文字 -->
    <p class="form-description">所有内容都不允许为空，最多可以上传6张图片</p>

    <el-form
        ref="form"
        :model="form"
        class="responsive-form"
        label-position="left"
        label-width="120px"
    >
      <!-- 内容标题 -->
      <el-form-item label="内容标题" prop="contentTitle">
        <el-input v-model="form.contentTitle" placeholder="请输入内容标题"></el-input>
      </el-form-item>
      <el-form-item label="内容分类" prop="contentCategory">
        <el-select v-model="form.contentCategory" placeholder="请选择内容分类">
          <el-option label="南区操场" value="南区操场"></el-option>
          <el-option label="足球场" value="足球场"></el-option>
          <el-option label="南区篮球场" value="南区篮球场"></el-option>
          <el-option label="北区篮球场" value="北区篮球场"></el-option>
          <el-option label="南区体育馆" value="南区体育馆"></el-option>
          <el-option label="北区体育馆" value="北区体育馆"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否额外消费" prop="contentPrice">
        <el-select v-model="form.contentPrice" placeholder="请选择是否需要额外消费">
          <el-option label="是" value="是"></el-option>
          <el-option label="否" value="否"></el-option>
          <el-option label="分情况" value="分情况"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="内容描述" prop="contentDescription">
        <el-input v-model="form.contentDescription" placeholder="请输入内容描述" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="内容指引位置" prop="contentGuidePosition">
        <el-input v-model="form.contentGuidePosition" placeholder="请输入内容指引位置"></el-input>
      </el-form-item>
      <el-form-item label="内容图片" prop="contentImage">
        <el-upload
            :action=this.uploadUrl
            :before-upload="beforeUpload"
            :file-list="fileList"
            :limit="6"
            :on-change="handleChange"
            :on-error="handleError"
            :on-exceed="handleExceed"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            accept="image/*"
            list-type="picture-card"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {ElMessage} from "element-plus";
import axios from "axios";
import {inject} from "vue";

export default {
  setup() {
    const uploadUrl = inject("uploadUrl");
    return {uploadUrl};
  },
  data() {
    return {
      form: {
        contentTitle: '',
        contentCategory: '',
        contentPrice: '',
        contentDescription: '',
        contentGuidePosition: '',
        contentImage: [],
      },
      fileList: [],
      dialogImageUrl: '', // 预览图片的 URL
      dialogVisible: false, // 控制预览对话框的显示
    };
  },
  mounted() {
    this.getOriginalData();
  },
  methods: {
    //数据回显用于编辑
    getOriginalData() {
      const id = this.$route.query.playgroundId;
      axios.get('/playground/get/' + id)
          .then(response => {
            const originalData = response.data.data;
            this.form.contentTitle = originalData.contentTitle;
            this.form.contentCategory = originalData.contentCategory;
            this.form.contentPrice = originalData.contentPrice;
            this.form.contentDescription = originalData.contentDescription;
            this.form.contentGuidePosition = originalData.contentGuidePosition;
            this.form.contentImage = JSON.parse(originalData.contentImage); // 将字符串转换为数组
            // 将 contentImage 数组转换为 fileList 格式
            if (this.form.contentImage && this.form.contentImage.length > 0) {
              this.fileList = this.form.contentImage.map((url, index) => ({
                name: `image_${index + 1}`, // 文件名
                url: url, // 图片 URL
                status: 'success', // 上传状态
              }));
            } else {
              this.fileList = [];
            }
          })
          .catch(error => {
            console.error('获取数据失败', error);
          });
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 移除图片
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt8M = file.size / 1024 / 1024 < 8; // 文件大小限制为 8MB
      if (!isImage) {
        this.$message.error('只能上传图片格式的文件!');
        return false; // 阻止上传
      }
      if (!isLt8M) {
        this.$message.error('上传的图片大小不能超过 8MB!');
        return false; // 阻止上传
      }
      return true; // 允许上传
    },
    // 上传成功回调
    handleSuccess(response, file, fileList) {
      this.$message.success('上传成功');
      // 假设上传成功后，后端返回图片的 URL
      this.form.contentImage = response.data; // 设置图片 URL 到 form 中
      console.log(this.form.contentImage);
      this.fileList = fileList; // 更新 fileList 状态
      console.log('上传成功', response);
    },
    // 上传失败回调
    handleError(err, file, fileList) {
      this.$message.error('上传失败');
      console.error('上传失败', err);
    },
    // 超出上传限制时的回调
    handleExceed(files, fileList) {
      this.$message.warning('最多只能上传 1 张图片');
    },
    onSubmit() {
      if (this.form.contentTitle === '' || this.form.contentCategory === '' ||
          this.form.contentPrice === '' || this.form.contentDescription === ''
          || this.form.contentGuidePosition === '' || this.form.contentImage === '') {
        ElMessage.error('所有内容都不许为空哦');
        return;
      }
      const id = this.$route.query.playgroundId;
      axios.put('/playground/update/' + id, {
        contentTitle: this.form.contentTitle,
        contentCategory: this.form.contentCategory,
        contentPrice: this.form.contentPrice,
        contentDescription: this.form.contentDescription,
        contentGuidePosition: this.form.contentGuidePosition,
        contentImage: JSON.stringify(this.form.contentImage), // 转换为 JSON 字符串,
      })
          .then(response => {
            console.log(response.data);
            ElMessage.success('添加成功');
            this.$router.push('/user/home');
          })
          .catch(error => {
            console.error(error);
            ElMessage.error('添加失败');
          });
    },
    handleChange(file, fileList) {
      // 检查文件是否有效
      if (!file || !file.raw) {
        return;
      }

      // 如果是新增文件，将其 URL 添加到 form.contentImage 数组中
      // 假设文件上传组件的 `on-success` 回调会更新 form.contentImage
      // 这里我们先将文件对象存储起来，等待上传成功后再更新 URL
      if (file.status === 'ready') {
        // 如果是新增文件，先将文件对象存储起来
        this.form.contentImage.push(file.raw);
      }

      // 更新 fileList 状态
      this.fileList = fileList;

      // 如果需要在文件添加时立即显示预览，可以在这里处理
      // 例如，如果文件是图片，可以使用 FileReader 读取文件并显示预览
      if (file.raw.type.startsWith('image/')) {
        const reader = new FileReader();
        reader.onload = (e) => {
          file.url = e.target.result; // 设置文件的预览 URL
        };
        reader.readAsDataURL(file.raw);
      }
    },
  }
}
</script>

<style scoped>
.form-container {
  margin: 20px 0; /* 调整外边距，使其向左对齐 */
  padding: 20px;
}

/* 添加标题样式 */
.header {
  background: none;
  padding-top: 5px;
  text-align: left;
  font-size: 20px;
  line-height: 30px;
  font-weight: bold;
}

/* 添加带下划线的文字样式 */
.form-description {
  border-bottom: 1px solid #ddd;
  padding-bottom: 5px;
  color: #666;
  text-align: left;
  line-height: 25px; /* 设置行高 */
}

.responsive-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 强制设置 placeholder 字体为 Zpix */
.form-container ::placeholder {
  font-family: "Zpix", sans-serif !important;
}

/* 强制设置输入框内容的字体为 Zpix */
.form-container input {
  font-family: "Zpix", sans-serif !important;
}
</style>